package com.chengxiaoxiao.utils.db;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class DBCPUtil {

    private static DataSource dataSource;

    static {
        try {
            InputStream in = DBCPUtil.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties ps = new Properties();
            ps.load(in);

            dataSource =BasicDataSourceFactory.createDataSource(ps);
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    /**
     * huoqu 得到数据库数据源
     * @return
     */
    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 获取数据库链接
     * @return
     */
    public static Connection getConnection()
    {
        try {
            return dataSource.getConnection();
        } catch (Exception e) {
            throw new RuntimeException("获取数据库链接错误");
        }
    }
}
